package com.kili.file.config;

import com.kili.file.common.IConstants;
import com.kili.file.filter.FileUploadValidationFilter;
import com.kili.file.config.elect.DynamicElectResolver;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

/**
 * AppWebMvcConfigurer
 *
 * @author Gordon
 * @version 2019/4/9
 */
@Configuration
public class AppWebMvcConfigurer implements WebMvcConfigurer {

    @Value("${local.path}")
    private String path;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //  add mapping path and specify an external path
        registry.addResourceHandler(IConstants.LOCAL_STORAGE_MAPPING_PATH + "/**").addResourceLocations("file:" + path);
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(dynamicElectResolver());
    }

    /**
     * @return 实例化动态选举
     */
    @Bean
    public DynamicElectResolver dynamicElectResolver() {
        return new DynamicElectResolver();
    }


    /**
     * @author Gordon
     * @since 2019/07/25
     */
    class FileUploadFilterRegistrationConfig {

        @Resource
        private MultipartResolver multipartResolver;

        @Bean
        public FilterRegistrationBean filterInitialized() {
            FileUploadValidationFilter fileUploadValidationFilter = new FileUploadValidationFilter(multipartResolver);
            FilterRegistrationBean<FileUploadValidationFilter> filterBean = new FilterRegistrationBean<>();
            filterBean.setFilter(fileUploadValidationFilter);
            //The smaller the value, the higher the priority
            filterBean.setOrder(-1);
            filterBean.setName("FileValidFilter");
            filterBean.setUrlPatterns(Collections.singletonList(IConstants.FILTER_URI));
            fileUploadValidationFilter.setMultipartResolver(multipartResolver);
            return filterBean;
        }
    }

}
